#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QMenu>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QStringList strLists;
    strLists << "item1" << "item2" << "item3";

    ui->listWidget->addItems(strLists);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_toolBox_currentChanged(int index)
{
    ui->tabWidget->setCurrentIndex(index);
}

void MainWindow::on_actListIni_triggered()
{
    qDebug() << "actListIni called...";
}

void MainWindow::on_actListInsert_triggered()
{
    QListWidgetItem *item;
    bool chk = ui->checkBox->isChecked();

    for(int i = 0; i < 20; i++)
    {
        QString str = QString::asprintf("insert item %d", i);
        item = new QListWidgetItem(str);
        item->setCheckState(Qt::Checked);
        if(chk)
        {
            item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsUserCheckable
                           | Qt::ItemIsEnabled);
        } else {
            item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable
                           | Qt::ItemIsEnabled);
        }
        ui->listWidget->addItem(item);
    }
}

void MainWindow::on_actListClear_triggered()
{
    ui->listWidget->clear();
}

void MainWindow::on_actListDelete_triggered()
{
    if(ui->listWidget->currentItem()) {
        delete ui->listWidget->takeItem(ui->listWidget->currentRow());
    }
}



void MainWindow::on_checkBox_clicked(bool checked)
{
    int cnt = ui->listWidget->count();
    for(int i = 0; i < cnt; ++i)
    {
        QListWidgetItem* item = ui->listWidget->item(i);
        if(checked)
        {
            item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsUserCheckable
                           | Qt::ItemIsEnabled);
        } else {
            item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable
                           | Qt::ItemIsEnabled);
        }
    }
}

void MainWindow::on_listWidget_customContextMenuRequested(const QPoint &pos)
{
    QMenu *menuList = new QMenu(this);

    menuList->addAction(ui->actListIni);
    menuList->addAction(ui->actListClear);
    menuList->addAction(ui->actListDelete);
    menuList->addAction(ui->actListInsert);

    menuList->exec(QCursor::pos());

    if(menuList)
    {
        delete menuList;
        menuList = NULL;
    }
}

void MainWindow::on_listWidget_itemChanged(QListWidgetItem *item)
{
    qDebug() << "item chanage, new text: " << item->text();
}

void MainWindow::on_listWidget_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    QString str;
    if(current)
    {
        if(!previous)
            str = "当前项:" + current->text();
        else
            str = "前一项:" + previous->text() + "当前项:" + current->text();
        ui->lineEdit->setText(str);
    }
}
